package org.dualr.litelog.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.dualr.litelog.entity.Comment;

public class CommentDao {
	private static CommentDao _instance = null;

	public static CommentDao getInstance() {
		if (_instance == null) {
			_instance = new CommentDao();
		}
		return _instance;
	}

	//insert
	public String insert(Comment comment) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(comment);
		} finally {
			pm.close();
		}
		return comment.getId().toString();
	}

	// delete
	@SuppressWarnings("unchecked")
	public void deleteById(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Comment.class);
		query.setFilter("id == idParam");
		query.declareParameters("Long idParam");
		List<Comment> comments = (List<Comment>) pm.newQuery(query).execute(
				id);
		try {
			for (Comment comment : comments) {
				pm.deletePersistent(comment);
			}
		} finally {
			pm.close();
		}
		
	}
	//
	public Comment getById(Long id){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Comment comment = null;
		try{
			comment  = pm.getObjectById(Comment.class,id);
		}finally{
			pm.close();
		}
		return comment;
	}

	// 
	@SuppressWarnings("unchecked")
	public List<Comment> getCommentByPostId(Long postId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Comment.class);
		query.setFilter("postId == postIdParam");
		query.declareParameters("Long postIdParam");
		query.setOrdering("commentDate desc");
		List<Comment> commentList = null;
		try {
			commentList = (List<Comment>) query.execute(postId);
			return commentList;
		} finally {
			query.closeAll();
		}
	}

	public int getCommentCount(Long articleId) {
		String sql = "SELECT count(id) FROM atta.blog.bean.Comment where articleId =="
				+ articleId;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(sql);
		int i;
		try {
			i = (Integer) query.execute();
			return i;
		} finally {
			query.closeAll();
		}
	}

	//
	@SuppressWarnings("unchecked")
	public List<Comment> getCommentByRange(int indexStart, int indexEnd) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Comment.class);
		query.setRange(indexStart, indexEnd);
		query.setOrdering("commentDate desc");
		List<Comment> comments = null;
		try {
			comments = (List<Comment>) query.execute();
			return comments;
		} finally {
			query.closeAll();
		}
	}

	/**
	 * @return
	 */
	public int getCount() {
		String sql = "SELECT count(id) FROM org.dualr.litelog.entity.Comment";
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(sql);
		int i;
		try {
			i = (Integer) query.execute();
			return i;
		} finally {
			query.closeAll();
		}
	}
}
